package com.suning.sawp.in.controller.model;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.suning.sawp.constants.ExportConstants;
import com.suning.sawp.constants.LoggerConstants;
import com.suning.sawp.dto.common.EmployeeInfo;
import com.suning.sawp.dto.common.OrgInfo;
import com.suning.sawp.dto.common.QueryResult;
import com.suning.sawp.dto.common.ReturnMsg;
import com.suning.sawp.dto.oss.ExportTaskDto;
import com.suning.sawp.exception.SawpException;
import com.suning.sawp.in.controller.DjBaseController;
import com.suning.sawp.in.controller.MyGsonView;
import com.suning.sawp.in.filter.RequestUserHolder;
import com.suning.sawp.intf.maindiscode.MainDiscodeService;
import com.suning.sawp.intf.model.DownloadModelListBean;
import com.suning.sawp.intf.model.ModelBean;
import com.suning.sawp.intf.model.ModelEffectiveness;
import com.suning.sawp.intf.model.ModelErrorConstant;
import com.suning.sawp.intf.model.ModelExptBean;
import com.suning.sawp.intf.model.ModelManageService;
import com.suning.sawp.intf.model.SaleModelExptBean;
import com.suning.sawp.intf.store.StoreInfoService;
import com.suning.sawp.po.store.StoreInfo;
import com.suning.sawp.service.impl.model.ModelManageServiceImpl;
import com.suning.sawp.service.util.ExportFileUtil;

/**
 * 
 * 〈一句话功能简述〉<br>
 * 〈功能详细描述〉
 *
 * @author Wuxiao
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@RequestMapping("/adminPage/model")
@Controller
public class ModelManageController extends DjBaseController {

    @Resource
    ModelManageService modelManageService;

    @Resource
    StoreInfoService storeInfoService;
    
    @Resource
    MainDiscodeService mainDiscodeService;
    
    @Resource
    MongoTemplate mongoTemplate;
    
    @Resource
    ExportFileUtil exportFileUtil;

    private static final Logger LOGGER = LoggerFactory.getLogger(LoggerConstants.SAWP_SERVICE);
    
    /**
     * 
     * 功能描述: 查询样机清单列表<br>
     * 〈功能详细描述〉
     *
     * @param regionCode 大区
     * @param branchCode 分公司
     * @param commCode 商品编码/名称
     * @param storeCode 门店编码
     * @param pageNo
     * @param pageSize
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryList.do")
    public MyGsonView queryModelList(String regionCode, String branchCode, String commCode, String storeCode, Integer pageNo, Integer pageSize,String status,String categoryCode,String brandCode) {
        ReturnMsg<QueryResult<ModelBean>> ret = new ReturnMsg<QueryResult<ModelBean>>();
        if (StringUtils.isBlank(regionCode)) {
            ret.setError(ModelErrorConstant.MODEL_ERR_E006, ModelErrorConstant.MODEL_ERR_MAP);
            return setGsonView(ret);
        }
        EmployeeInfo employeeInfo = RequestUserHolder.getRequestUser();
        if (OrgInfo.ORG_LEVEL.REGION_LEVEL.equals(employeeInfo.getOrgLevel())) {
            if (!regionCode.equals(employeeInfo.getRegionCode())) {
                ret.setError(ModelErrorConstant.MODEL_ERR_E006, ModelErrorConstant.MODEL_ERR_MAP);
                return setGsonView(ret);
            }
        }
        if (StringUtils.isBlank(storeCode) || checkStoreCode(storeCode)) {
            try {
                ret = modelManageService.queryModelList(regionCode, branchCode, commCode, storeCode, pageNo, pageSize,status, categoryCode, brandCode);
            } catch (Exception e) {
                ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
                LOGGER.error(String.format("后台查询门店样机列表异常,大区编码：%s, 分公司编码：%s, 商品：%s, 门店编码：%s", regionCode, branchCode,
                        commCode, storeCode), e);
            }
        } else {
            ret.setError(ModelErrorConstant.MODEL_ERR_E006, ModelErrorConstant.MODEL_ERR_MAP);
        }
        return setGsonView(ret);
    }
    
    @RequestMapping("/queryDownloadMonths.do")
    public MyGsonView queryDownloadMonths() {
        ReturnMsg<List<DownloadModelListBean>> ret = new ReturnMsg<List<DownloadModelListBean>>();
        try {
            ret = modelManageService.queryDownloadMonths();
        } catch (Exception e) {
            ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
            LOGGER.error("queryDownloadMonths error ",e);
        }
    
        return setGsonView(ret);
    }
    
    @RequestMapping("/queryDownloadUrlList.do")
    public MyGsonView queryDownloadUrlList(String month) {
        ReturnMsg<List<DownloadModelListBean>> ret = new ReturnMsg<List<DownloadModelListBean>>();
        try {
            ret = modelManageService.queryDownloadUrlList(month);
        } catch (Exception e) {
            ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
            LOGGER.error("queryDownloadMonths error ",e);
        }
    
        return setGsonView(ret);
    }
    

    /**
     * 
     * 功能描述:查询样机异常清单 <br>
     * 〈功能详细描述〉
     *
     * @param regionCode 大区非空
     * @param branchCode 分公司
     * @param storeCode 门店
     * @param pageNo
     * @param pageSize
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryExptList.do")
    public MyGsonView queryExptList(String regionCode, String branchCode, String storeCode, Integer pageNo,
            Integer pageSize) {
        ReturnMsg<QueryResult<ModelExptBean>> ret = new ReturnMsg<QueryResult<ModelExptBean>>();
        if (StringUtils.isBlank(regionCode)) {
            ret.setError(ModelErrorConstant.MODEL_ERR_E001, ModelErrorConstant.MODEL_ERR_MAP);
            return setGsonView(ret);
        }
        // 是否有门店的查看权限
        if (StringUtils.isNotBlank(storeCode) && !checkStoreCode(storeCode)) {
            ret.setError(ModelErrorConstant.MODEL_ERR_E006, ModelErrorConstant.MODEL_ERR_MAP);
            return setGsonView(ret);
        }
        try {
            ret = modelManageService.queryModelExptList(regionCode, branchCode, storeCode, pageNo, pageSize);
        } catch (Exception e) {
            ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
            LOGGER.error("queryExptList failed.regionCode:{}, branchCode:{}, storeCode:{}, pageNo:{}, pageSize:{}",
                    regionCode, branchCode, storeCode, pageNo, pageSize);
        }
        return setGsonView(ret);
    }

    /**
     * 
     * 功能描述:查询财务样机异常列表<br>
     * 〈功能详细描述〉
     *
     * @param storeCode
     * @param pageNo
     * @param pageSize
     * @param isInStorage
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/querySaleExptList.do")
    public MyGsonView querySaleExptList(String regionCode, String branchCode, String storeCode, Integer pageNo,
            Integer pageSize, Integer isInStorage) {
        ReturnMsg<QueryResult<SaleModelExptBean>> ret = new ReturnMsg<QueryResult<SaleModelExptBean>>();
        if (StringUtils.isBlank(regionCode)) {
            ret.setError(ModelErrorConstant.MODEL_ERR_E001, ModelErrorConstant.MODEL_ERR_MAP);
            return setGsonView(ret);
        }
        // 是否有门店的查看权限
        if (StringUtils.isNotBlank(storeCode) && !checkStoreCode(storeCode)) {
            ret.setError(ModelErrorConstant.MODEL_ERR_E006, ModelErrorConstant.MODEL_ERR_MAP);
            return setGsonView(ret);
        }
        try {
            ret = modelManageService.querySaleModelExptList(regionCode, branchCode, storeCode, pageNo, pageSize,
                    isInStorage);
        } catch (Exception e) {
            ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
            LOGGER.error(String.format("后台查询财务样机异常清单列表异常,门店编码:%s,", storeCode), e);
        }
        return setGsonView(ret);
    }

    private boolean checkStoreCode(String storeCode) {
        if (StringUtils.isBlank(storeCode)) {
            return false;
        }
        EmployeeInfo requestUser = RequestUserHolder.getRequestUser();
        // 门店级别只能查看自己所属门店
        if (OrgInfo.ORG_LEVEL.STORE_LEVEL.equals(requestUser.getOrgLevel())) {
            return storeCode.equals(requestUser.getStoreCode());
        } else if (OrgInfo.ORG_LEVEL.COMPANY_LEVEL.equals(requestUser.getOrgLevel())) {
            StoreInfo storeInfo = storeInfoService.queryStoreByCode(storeCode);
            return storeInfo != null && StringUtils.isNotBlank(storeInfo.getSaleBranchCode()) 
                    && storeInfo.getSaleBranchCode().equals(requestUser.getBranchCode());
        } else if (OrgInfo.ORG_LEVEL.REGION_LEVEL.equals(requestUser.getOrgLevel())) {
            StoreInfo storeInfo = storeInfoService.queryStoreByCode(storeCode);
            return storeInfo != null && StringUtils.isNotBlank(storeInfo.getRegionCode())
                    && storeInfo.getRegionCode().equals(requestUser.getRegionCode());
        } else {
            return true;
        }
    }

    /**
     * 
     * 功能描述: 样机有效性查询(样机单品分析)<br>
     * 〈功能详细描述〉
     *
     * @param regionCode
     * @param branchCode
     * @param brandCode
     * @param categoryCode
     * @param storeCode
     * @param comRangeName
     * @param comGroupName
     * @param commCode
     * @param pageNo
     * @param pageSize
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/effectiveList.do")
    public MyGsonView queryModelEffect(String regionCode, String branchCode, String brandCode, String categoryCode,
            String storeCode, String comRangeName, String comGroupName, String commCode, String month,
            Integer pageNo, Integer pageSize) {
        ReturnMsg<QueryResult<ModelEffectiveness>> ret = new ReturnMsg<QueryResult<ModelEffectiveness>>();
        try {
            ret = modelManageService.queryModelEffectListEx(regionCode, branchCode, storeCode, brandCode, categoryCode,
                    comRangeName, comGroupName, commCode, month, null, pageNo, pageSize);
        } catch (Exception e) {
            ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
            LOGGER.error(String.format(
                    "ModelManageController queryModelEffect error,brandCode:%s,categoryCode:%s,storeCode:%s",
                    brandCode, categoryCode, storeCode), e);
        }
        return setGsonView(ret);
    }

    /**
     * 
     * 功能描述: 样机清单导出<br>
     * 〈功能详细描述〉
     *
     * @param response
     * @param regionCode 大区编码 必填项(20170412Add)
     * @param branchCode 分公司编码(20170412Add)
     * @param commCode 商品编码(20170412Add)
     * @param storeCode 门店编码
     * @param index
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/exportModel.do")
    public void exportExcelModelByStore(HttpServletResponse response, String regionCode, String branchCode,
            String commCode, String storeCode, @RequestParam(defaultValue = "1") Integer index) {
        try {
            if (StringUtils.isBlank(regionCode)) {
                response.setContentType("text/html; charset=UTF-8");
                response.setHeader("Cache-Control", "no-cache");
                response.getOutputStream().write(ModelErrorConstant.MODEL_ERR_MAP.get(ModelErrorConstant.MODEL_ERR_E001).getBytes());
            } else if (modelManageService.overExportModelTimes()) {
                // 判断是否超过导出次数(每天50次)
                response.setContentType("text/html; charset=UTF-8");
                response.setHeader("Cache-Control", "no-cache");
                response.getOutputStream().write(ModelErrorConstant.MODEL_ERR_MAP.get(ModelErrorConstant.MODEL_ERR_E008).getBytes());
            } else {
                // 设置返回输出流
                response.setContentType("application/octet-stream");
                response.setCharacterEncoding("UTF-8");
                response.setHeader("Content-disposition", "attachment; filename=" + "modelList-" + regionCode + "-" + index
                        + ".xlsx");
                modelManageService.exportExcelModelByStore(regionCode, branchCode, commCode, storeCode, index,
                        response.getOutputStream());
                // 导出成功，导出次数+1
                modelManageService.addExportModelTime();
            }
            response.getOutputStream().flush();
            response.getOutputStream().close();
        } catch (IOException e) {
            LOGGER.error("样机管理-后台-导出-样机清单异常", e);
        }
    }
    
    /**
     * 
     * 功能描述: 样机清单导出<br>
     * 〈功能详细描述〉
     *
     * @param response
     * @param regionCode 大区编码 必填项(20170412Add)
     * @param branchCode 分公司编码(20170412Add)
     * @param commCode 商品编码(20170412Add)
     * @param storeCode 门店编码
     * @param index
     * @throws IOException 
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/exportModelEx.do")
    public void exportExcelModelByStoreEx(HttpServletResponse response, String regionCode, String branchCode,
            String commCode, String storeCode, @RequestParam(defaultValue = "1") Integer index,String status,String categoryCode,String brandCode) throws IOException {
        EmployeeInfo employeeInfo = RequestUserHolder.getRequestUser();
        OutputStream ouputStream = null;
        try {
            response.setContentType("text/html; charset=UTF-8");
            response.setHeader("Cache-Control", "no-cache");            
            ouputStream = response.getOutputStream();
            if (StringUtils.isBlank(regionCode)) {
                ouputStream.write(ModelErrorConstant.MODEL_ERR_MAP.get(ModelErrorConstant.MODEL_ERR_E001).getBytes());
            } else {
                if (null == employeeInfo || StringUtils.isBlank(employeeInfo.getStaffId())) {
                    LOGGER.error("exportExcelModelByStoreEx.employeeInfo or staffId is null. employeeInfo:{}", employeeInfo);
                    ouputStream.write(ModelErrorConstant.MODEL_ERR_MAP.get(ModelErrorConstant.MODEL_ERR_E001).getBytes());
                } else {
                    String staffId = employeeInfo.getStaffId();
                    String className = ModelManageServiceImpl.class.getName(); 
                    String methodName = ExportConstants.ExportMethodName.EXPORT_EXCEL_MODEL_BY_STORE_EX;
                    @SuppressWarnings("unchecked")
                    List<Object> params =  new ArrayList<Object>(Arrays.asList(staffId, regionCode, branchCode, commCode, storeCode, index, status, categoryCode, brandCode));
                    List<String> paramsType = new ArrayList<String>(Arrays.asList(String.class.getName(), String.class.getName(),
                            String.class.getName(), String.class.getName(), String.class.getName(), Integer.class.getName(), String.class.getName(), String.class.getName(), String.class.getName()));
                    ExportTaskDto dto = new ExportTaskDto(staffId, className, methodName, params, paramsType);
                    mongoTemplate.save(dto);
                    ouputStream.write(ExportConstants.MODEL_EXPORT_TIPS_MAP.get(ExportConstants.TIP_T001).getBytes());
                }
            }
        } catch (IOException e) {
            LOGGER.error("exportModelEx 导出excel出错", e);
            throw new SawpException(ExportConstants.MODEL_EXPORT_ERR_MAP.get(ExportConstants.ERR_E999));
            }    finally{
            if(ouputStream!=null){
                ouputStream.flush();    
                ouputStream.close();
            }
        }
    }

    /**
     * 功能描述: <br>
     * 异常样机清单导出
     */
    @Deprecated
//    @RequestMapping("/exportExptList.do")
    public void exportExcelModelExptByStore(HttpServletResponse response, String storeCode,
            @RequestParam(defaultValue = "1") Integer index) {
        try {
            // 设置返回输出流
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-disposition",
                    "attachment; filename=" + "probModelList-" + storeCode + "-" + index + ".xlsx");
            modelManageService.exportExcelModelExptByStore(storeCode, index, response.getOutputStream());
            response.getOutputStream().flush();
            response.getOutputStream().close();
        } catch (IOException e) {
            LOGGER.error("样机管理-后台-导出-异常样机清单异常", e);
        }
    }
    
    /**
     * 功能描述: <br>
     * 异常样机清单导出
     */
    @RequestMapping("/exportExptList.do")
    public void exportExcelModelExptByStoreEx(HttpServletResponse response, String regionCode, String branchCode,
            String storeCode, @RequestParam(defaultValue = "1") Integer index) {
        EmployeeInfo employeeInfo = RequestUserHolder.getRequestUser();
        OutputStream ouputStream = null;
        try {
            ouputStream = response.getOutputStream();
            if (StringUtils.isBlank(regionCode) || index == null) {
                LOGGER.error("exportExcelModelExptByStoreEx.Paramter is null. regionCode:{}, index:{}", regionCode, index);
                ouputStream.write(ExportConstants.MODEL_EXPORT_ERR_MAP.get(ExportConstants.ERR_E001).getBytes());
                return;
            } else if (null == employeeInfo || StringUtils.isBlank(employeeInfo.getStaffId())) {
                LOGGER.error("exportExcelModelExptByStoreEx.employeeInfo or staffId is null. employeeInfo:{}", employeeInfo);
                ouputStream.write(ExportConstants.MODEL_EXPORT_ERR_MAP.get(ExportConstants.ERR_E002).getBytes());
                return;
            } else {
                String staffId = employeeInfo.getStaffId();
                String className = ModelManageServiceImpl.class.getName();
                String methodName = ExportConstants.ExportMethodName.EXPORT_EXCEL_MODEL_EXPT_BY_STORE_EX;
                @SuppressWarnings("unchecked")
                List<Object> params = new ArrayList<Object>(
                        Arrays.asList(staffId, regionCode, branchCode, storeCode, index));
                exportFileUtil.saveExportTask(staffId, className, methodName, params);
                ouputStream.write(ExportConstants.MODEL_EXPORT_TIPS_MAP.get(ExportConstants.TIP_T001).getBytes());
            }
        } catch (IOException e) {
            LOGGER.error("exportExcelModelExptByStoreEx failed.", e);
            throw new SawpException(ExportConstants.MODEL_EXPORT_ERR_MAP.get(ExportConstants.ERR_E999));
        } finally {
            try {
                if (null != ouputStream) {
                    ouputStream.flush();
                    ouputStream.close();
                }
            } catch (IOException e) {
                LOGGER.error("exportExcelModelExptByStoreEx finally failed.", e);
            }
        }
    }

    /**
     * 
     * 功能描述: 财务异常清单导出<br>
     * 〈功能详细描述〉
     *
     * @param storeCode
     * @param index
     * @param response
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @Deprecated
//    @RequestMapping("/exportSaleExpt.do")
    public void exportSaleModelExpt(String storeCode, Integer index, Integer isInStorage,
            HttpServletResponse response) {
        OutputStream ouputStream = null;
        try {
            if (StringUtils.isBlank(storeCode) || index == null) {
                response.setContentType("text/html; charset=UTF-8");
                response.setHeader("Cache-Control", "no-cache");
                ouputStream = response.getOutputStream();
                ouputStream.write(ModelErrorConstant.MODEL_ERR_MAP.get(ModelErrorConstant.MODEL_ERR_E001).getBytes());
            } else {
                Workbook workbook = modelManageService.exportSaleModelExpt(storeCode, index, isInStorage);
                if (workbook == null) {
                    response.setContentType("text/html; charset=UTF-8");
                    response.setHeader("Cache-Control", "no-cache");
                    ouputStream = response.getOutputStream();
                    ouputStream
                            .write(ModelErrorConstant.MODEL_ERR_MAP.get(ModelErrorConstant.MODEL_ERR_E007).getBytes());
                } else {
                    response.setContentType("application/x-download");
                    response.setHeader("Content-disposition", "attachment;filename=saleModelExpt_" + index + ".xlsx");
                    ouputStream = response.getOutputStream();
                    workbook.write(ouputStream);
                }
            }
            ouputStream.flush();
            ouputStream.close();
        } catch (Exception e) {
            LOGGER.error("exportSaleModelExpt 导出excel出错", e);
        } finally {
            modelManageService.endExportExcel();
        }
    }
    
    /**
     * 
     * 功能描述: 财务异常清单导出<br>
     * 〈功能详细描述〉
     *
     * @param storeCode
     * @param index
     * @param response
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/exportSaleExpt.do")
    public void exportSaleModelExptEx(String regionCode, String branchCode, String storeCode, Integer index,
            Integer isInStorage, HttpServletResponse response) {
        EmployeeInfo employeeInfo = RequestUserHolder.getRequestUser();
        OutputStream ouputStream = null;
        try {
            ouputStream = response.getOutputStream();
            if (StringUtils.isBlank(regionCode) || index == null) {
                LOGGER.error("exportExcelModelExptByStoreEx.Paramter is null. regionCode:{}, index:{}", regionCode, index);
                ouputStream.write(ExportConstants.MODEL_EXPORT_ERR_MAP.get(ExportConstants.ERR_E001).getBytes());
                return;
            } else if (null == employeeInfo || StringUtils.isBlank(employeeInfo.getStaffId())) {
                LOGGER.error("exportExcelModelExptByStoreEx.employeeInfo or staffId is null. employeeInfo:{}", employeeInfo);
                ouputStream.write(ExportConstants.MODEL_EXPORT_ERR_MAP.get(ExportConstants.ERR_E002).getBytes());
                return;
            } else {
                String staffId = employeeInfo.getStaffId();
                String className = ModelManageServiceImpl.class.getName();
                String methodName = ExportConstants.ExportMethodName.EXPORT_SALE_MODEL_EXPT_EX;
                @SuppressWarnings("unchecked")
                List<Object> params = new ArrayList<Object>(Arrays.asList(staffId, regionCode, branchCode, storeCode, index, isInStorage));
                exportFileUtil.saveExportTask(staffId, className, methodName, params);
                ouputStream.write(ExportConstants.MODEL_EXPORT_TIPS_MAP.get(ExportConstants.TIP_T001).getBytes());
            }
        } catch (IOException e) {
            LOGGER.error("exportExcelModelExptByStoreEx failed.", e);
            throw new SawpException(ExportConstants.MODEL_EXPORT_ERR_MAP.get(ExportConstants.ERR_E999));
        } finally {
            try {
                if (null != ouputStream) {
                    ouputStream.flush();
                    ouputStream.close();
                }
            } catch (IOException e) {
                LOGGER.error("exportExcelModelExptByStoreEx finally failed.", e);
            }
        }
    }

    /**
     * 
     * 功能描述: 样机有效性导出<br>
     * 〈功能详细描述〉
     *
     * @param storeCode
     * @param index
     * @param response
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
//    @RequestMapping("/exptModelEffect.do")
    @Deprecated
    public void exptModelEffect(@RequestParam(value="regionCode") String regionCode, @RequestParam(value="branchCode", required = false)String branchCode, 
            @RequestParam(value = "brandCode", required = false) String brandCode,@RequestParam(value = "categoryCode", required = false) String categoryCode, 
            @RequestParam(value = "storeCode", required = false) String storeCode, @RequestParam(value = "comRangeName", required = false) String comRangeName, 
            @RequestParam(value = "comGroupName", required = false) String comGroupName, 
            @RequestParam(value = "commCode", required = false) String commCode, @RequestParam("index") Integer index, HttpServletResponse response) {
        OutputStream ouputStream = null;
        try {
            if (StringUtils.isBlank(regionCode) || index == null) {
                response.setContentType("text/html; charset=UTF-8");
                response.setHeader("Cache-Control", "no-cache");
                ouputStream = response.getOutputStream();
                ouputStream.write(ModelErrorConstant.MODEL_ERR_MAP.get(ModelErrorConstant.MODEL_ERR_E001).getBytes());
            } else {
                Workbook workbook = modelManageService.exportModelEffect(regionCode, branchCode, brandCode,
                        categoryCode, storeCode, comRangeName, comGroupName, commCode, index);
                if (workbook == null) {
                    response.setContentType("text/html; charset=UTF-8");
                    response.setHeader("Cache-Control", "no-cache");
                    ouputStream = response.getOutputStream();
                    ouputStream
                            .write(ModelErrorConstant.MODEL_ERR_MAP.get(ModelErrorConstant.MODEL_ERR_E007).getBytes());
                } else {
                    response.setContentType("application/x-download");
                    response.setHeader("Content-disposition", "attachment;filename=modelEffect_" + index + ".xlsx");
                    ouputStream = response.getOutputStream();
                    workbook.write(ouputStream);
                }
            }
            ouputStream.flush();
            ouputStream.close();
        } catch (Exception e) {
            LOGGER.error("exptModelEffect 导出excel出错", e);
        } finally {
            modelManageService.endExportExcel();
        }
    }
    
    /**
     * 
     * 功能描述: 样机有效性导出<br>
     * 〈功能详细描述〉
     *
     * @param storeCode
     * @param index
     * @param response
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/exptModelEffect.do")
    public void exptModelEffectEx(@RequestParam(value = "regionCode") String regionCode,
            @RequestParam(value = "branchCode", required = false) String branchCode,
            @RequestParam(value = "brandCode", required = false) String brandCode,
            @RequestParam(value = "categoryCode", required = false) String categoryCode,
            @RequestParam(value = "storeCode", required = false) String storeCode,
            @RequestParam(value = "comRangeName", required = false) String comRangeName,
            @RequestParam(value = "comGroupName", required = false) String comGroupName,
            @RequestParam(value = "commCode", required = false) String commCode, @RequestParam("index") Integer index,
            @RequestParam(value = "month", required = false) String month,
            @RequestParam(value = "storeType", required = false) String storeType, HttpServletResponse response) {
        EmployeeInfo employeeInfo = RequestUserHolder.getRequestUser();
        OutputStream ouputStream = null;
        try {
            ouputStream = response.getOutputStream();
            if (StringUtils.isBlank(regionCode) || index == null) {
                LOGGER.error("exptModelEffectEx.Paramter is null. regionCode:{}, index:{}", regionCode, index);
                ouputStream.write(ExportConstants.MODEL_EXPORT_ERR_MAP.get(ExportConstants.ERR_E001).getBytes());
                return;
            } else if (null == employeeInfo || StringUtils.isBlank(employeeInfo.getStaffId())) {
                LOGGER.error("exptModelEffectEx.employeeInfo or staffId is null. employeeInfo:{}", employeeInfo);
                ouputStream.write(ExportConstants.MODEL_EXPORT_ERR_MAP.get(ExportConstants.ERR_E002).getBytes());
                return;
            } else {
                String staffId = employeeInfo.getStaffId();
                String className = ModelManageServiceImpl.class.getName();
                String methodName = ExportConstants.ExportMethodName.EXPORT_MODEL_EFFECT_EX;
                @SuppressWarnings("unchecked")
                List<Object> params = new ArrayList<Object>(Arrays.asList(staffId, regionCode, branchCode, brandCode,
                        categoryCode, storeCode, comRangeName, comGroupName, commCode, index, month, storeType));
                exportFileUtil.saveExportTask(staffId, className, methodName, params);
                ouputStream.write(ExportConstants.MODEL_EXPORT_TIPS_MAP.get(ExportConstants.TIP_T001).getBytes());
            }
        } catch (IOException e) {
            LOGGER.error("exptModelEffectEx failed.", e);
            throw new SawpException(ExportConstants.MODEL_EXPORT_ERR_MAP.get(ExportConstants.ERR_E999));
        } finally {
            try {
                if (null != ouputStream) {
                    ouputStream.flush();
                    ouputStream.close();
                }
            } catch (IOException e) {
                LOGGER.error("exptModelEffectEx finally failed.", e);
            }
        }
    }

    /**
     * 
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryExptLimit.do")
    public MyGsonView queryExptLimit() {
        ReturnMsg<Integer> ret = new ReturnMsg<Integer>();
        try {
            ret = modelManageService.queryExptLimit();
        } catch (Exception e) {
            LOGGER.error("queryExptLimit error", e);
            ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
        }
        return setGsonView(ret);
    }
    
    /**
     * 
     * 功能描述: 导出CSV单个文件最大条数<br>
     * 〈功能详细描述〉默认5W
     *
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryExptCSVLimit.do")
    public MyGsonView queryExptCSVLimit() {
        ReturnMsg<Integer> ret = new ReturnMsg<Integer>();
        try {
            ret = modelManageService.queryExptCSVLimit();
        } catch (Exception e) {
            LOGGER.error("queryExptCSVLimit error", e);
            ret.setError(ModelErrorConstant.MODEL_ERR_E999, ModelErrorConstant.MODEL_ERR_MAP);
        }
        return setGsonView(ret);
    }
}
